package tech.aistar.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.aistar.pojo.Order;
import tech.aistar.service.OrderService;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;


    @GetMapping("/list")
    public List<Order> getAllOrder(){
        return orderService.getAll();
    }

    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody Order order) {
        try {
            Order createdOrder = orderService.createOrder(order);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", createdOrder);
            response.put("message", "订单创建成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(
                    Map.of("success", false, "message", "创建订单失败: " + e.getMessage())
            );
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getOrder(@PathVariable Long id) {
        Order order = orderService.getOrderById(id);
        if (order != null) {
            return ResponseEntity.ok(Map.of("success", true, "data", order));
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getUserOrders(@PathVariable Long userId) {
        List<Order> orders = orderService.getOrdersByUser(userId);
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", orders);
        response.put("count", orders.size());
        return ResponseEntity.ok(response);
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateStatus(@PathVariable Long id, @RequestBody Map<String, String> body) {
        String status = body.get("status");
        boolean success = orderService.updateOrderStatus(id, status);
        if (success) {
            return ResponseEntity.ok(Map.of("success", true, "message", "订单状态更新成功"));
        }
        return ResponseEntity.badRequest().body(
                Map.of("success", false, "message", "订单状态更新失败")
        );
    }

    @PostMapping("/{id}/cancel")
    public ResponseEntity<?> cancelOrder(@PathVariable Long id) {
        boolean success = orderService.cancelOrder(id);
        if (success) {
            return ResponseEntity.ok(Map.of("success", true, "message", "订单取消成功"));
        }
        return ResponseEntity.badRequest().body(
                Map.of("success", false, "message", "订单取消失败")
        );
    }
}
